package zhibi.wechat.mp.controller;

import com.github.pagehelper.PageInfo;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import zhibi.frame.domain.Page;
import zhibi.frame.mybatis.example.Example;
import zhibi.frame.mybatis.example.ExampleType;
import zhibi.wechat.mp.domain.NewsArticle;
import zhibi.wechat.mp.domain.NewsItem;
import zhibi.wechat.mp.extra.base.BaseController;
import zhibi.wechat.mp.service.NewsService;

import java.util.List;

import static zhibi.wechat.mp.extra.context.BaseConfig.REQUEST_PREFIX;

@Controller
@RequestMapping(REQUEST_PREFIX + "news")
public class WxMpNewController extends BaseController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private WxMpService wxMpService;

    /**
     * 图文资源列表
     *
     * @param newsItem
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(NewsItem newsItem, Page page, Model model) {
        Example example = Example.getInstance()
                .addOrder("createdTime", ExampleType.OrderType.DESC)
                .addParam("articles", newsItem.getArticles(), ExampleType.Operation.LIKE);
        PageInfo<NewsItem> pageInfo = newsService.selectByExample(example, page);
        setModelAttribute(model, pageInfo);
        return VIEW_PREFIX + "news/list";
    }

    @GetMapping("add")
    public String add() {
        return VIEW_PREFIX + "news/add";
    }

    @PostMapping("add")
    public String add(MultipartFile file, NewsArticle article) throws WxErrorException {
        if (null != file && !file.isEmpty()) {
            article.setThumbMediaId(saveImg(file));
        }
        String mediaId = newsService.insertArticle(article);
        //所有用户
        List<String> openids = wxMpService.getUserService().userList(null).getOpenids();
        WxMpMassOpenIdsMessage mpMassOpenIdsMessage = new WxMpMassOpenIdsMessage();
        mpMassOpenIdsMessage.setMediaId(mediaId);
        mpMassOpenIdsMessage.setToUsers(openids);
        mpMassOpenIdsMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
        wxMpService.getMassMessageService().massOpenIdsMessageSend(mpMassOpenIdsMessage);
        return redirect("list");
    }

}
